<script setup lang="ts">
import { getPatientInfo, getPayInfo, createOrder, pay } from '@/services/consult'
import { onMounted } from 'vue'
import { useConsultStore } from '@/stores'
import { ref } from 'vue'
import type { ConsultOrderPreData } from '@/types/consult'
import type { PatientItem } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onBeforeRouteLeave } from 'vue-router'
import { useRouter } from 'vue-router'

// 获取预支付信息
const consultStore = useConsultStore()
const payInfo = ref({} as ConsultOrderPreData)
const loadPayInfo = async () => {
  const res = await getPayInfo({
    type: consultStore.consult.type,
    illnessType: consultStore.consult.illnessType
  })
  payInfo.value = res.data
}

// 获取患者信息
const patientInfo = ref({} as PatientItem)
const loadPatientInfo = async () => {
  if (consultStore.consult.patientId) {
    const res = await getPatientInfo(consultStore.consult.patientId)
    patientInfo.value = res.data
  }
}

onMounted(() => {
  // 判断问诊信息是否存在
  if (!consultStore.consult.type) {
    // 问诊信息不存在
    return showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false // 回退页面时，不自动关闭弹窗
    }).then(() => {
      // 用户点击确定按钮
      // 跳转到首页
      router.push('/')
    })
  }

  // 获取预支付信息
  loadPayInfo()
  // 获取患者信息
  loadPatientInfo()
})

// 点击立即支付
const agree = ref(false)
const loading = ref(false)
const orderId = ref('')
const show = ref(false)
const toPay = async () => {
  // 校验是否勾选我已同意
  if (!agree.value) return showToast('请勾选我已同意')
  // 开启按钮loading
  loading.value = true
  try {
    // 调用生成订单接口
    const res = await createOrder(consultStore.consult)
    // 存储订单id
    orderId.value = res.data.id
    // 清空问诊信息
    consultStore.clear()
    // 打开支付抽屉
    show.value = true
  } finally {
    // 关闭按钮loading
    loading.value = false
  }
}

// 如果已经生成订单，不可回退
onBeforeRouteLeave(() => {
  if (orderId.value) {
    return false
  }
})

// 抽屉关闭之前的回调
const router = useRouter()
const beforeClose = async () => {
  // 关闭抽屉：return true
  // 不关闭抽屉： return false

  // 询问用户
  try {
    await showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付'
    })
    // 用户点击的是 继续支付
    // 不关闭支付抽屉
    return false
  } catch (error) {
    // 用户点击的是 仍要关闭
    // 跳转页面前，清空订单ID
    orderId.value = ''
    // 跳转到问诊订单页
    router.push('/user/consult')
    // 关闭抽屉
    return true
  }
}
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 预支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}.00`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}.00`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}.00`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="consultStore.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 底部操作栏 -->
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="toPay"
      :loading="loading"
    />
  </div>
  <!-- 支付抽屉 -->
  <cp-pay-sheet
    :show="show"
    :actualPayment="payInfo.actualPayment"
    :orderId="orderId"
    :before-close="beforeClose"
    payCallback="/room"
  ></cp-pay-sheet>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 0 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
</style>
